import sqlite3
from time import time,sleep
from lib.functions.exec import crezip
from lib.functions.sql import sort2
from os import listdir,remove,system
import webbrowser
from PIL import Image,ImageTk
import random as r
from configparser import ConfigParser
import threading


def main(id,name,old_path,new_path,retain_num,status):
    a = [id,name,old_path,new_path,retain_num,status]
    cf = ConfigParser()
    flag = 'True'
    db = sqlite3.connect('data.db')
    cur = db.cursor()
    cur.execute('SELECT * FROM backup where id == ? and name == ?',(id,name))
    db.commit()
    number=int(list(cur.fetchall())[0][2])
    while flag == 'True':
        cf.read('config.ini', encoding='utf-8')
        flag = cf.get('auto-backup','autobackup-status')
        ti = int(cf.get('backup-msg','Interval-time'))
        i = int(cf.get('backup-msg','execnum'))
        i+=1
        cf['backup-msg']['execnum']= str(i)
        with open('config.ini', 'w') as configfile:
            cf.write(configfile)
        print('---------------------------------------------------------------------------------')
        print('已执行%d次'%i)
        print('---------------------------------------------------------------------------------')
        try:
            if len(a) != 0:
                run(a,number)
                dele1(a,number)
                sleep(ti)
            else:
                sleep(ti)
        except:
            sleep(ti)
        number += 1
        cur.execute("UPDATE backup SET bkplastnum = ? where id == ? and name == ?",(number,id,name))
        db.commit()
        flag = cf.get('auto-backup','autobackup-status')

        
def run(a,num):
    try:
        start = time()
        print(a[2],'-->',a[3]+'\\'+a[1]+'--'+str(num)+'.zip')
        crezip(a[2],a[3]+'\\'+a[1]+'--'+str(num)+'.zip')
        end = time()
        print('---------------------------------------------------------------------------------')
        print('已备份'+a[1]+'--'+str(num)+'.zip,共耗时：%s Seconds'%(end-start))
        print('---------------------------------------------------------------------------------')
    except:
        print('---------------------------------------------------------------------------------')
        print('本次'+a[1]+'--'+str(num)+'.zip备份失败，已自动跳过本次备份')
        print('---------------------------------------------------------------------------------')  

def dele1(a,i):
    #try:
        print(a)
        paths = a[3]+'\\'+a[1]+'--'+str(i-int(a[4]))+'.zip'
        remove(paths)
    #except:



def sort(lst):
    n = len(lst)
    for i in range(n):
        for j in range(0, n-i-1):
            #计算索引j的文件编号
            x = lst[lst[j].rfind('-')+1:lst[j].rfind('.')]
            #计算索引j+1的文件编号
            y = lst[lst[j+1].find('-')+1:lst[j+1].rfind('.')]
            if x > y :
                lst[j], lst[j+1] = lst[j+1], lst[j]
    return lst
